package com.whfp.coky.ui.task.vm

import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import cn.bingoogolapple.qrcode.core.BarcodeType
import com.whfp.coky.App
import com.whfp.coky.R
import com.whfp.coky.databinding.ActivityScanCodeBinding
import com.whfp.coky.event.EventCode
import com.whfp.coky.event.EventMessage
import com.whfp.coky.other.Constants
import com.whfp.coky.ui.base.BaseActivity
import com.whfp.coky.ui.base.BaseViewModel
import com.whfp.coky.ui.task.model.TaskChildBean
import com.whfp.coky.utils.LogUtil

/**
 *
 *
 * created by coky on 2022/3/1
 */
class ScanCodeVM : BaseViewModel<ActivityScanCodeBinding>() {

    var result = MutableLiveData<String>()//扫码结果
    var scanType = MutableLiveData<String>()//扫码类型（外部传入）
    var isOpen = MutableLiveData(false)//是否开闪光
    var taskBean = MutableLiveData<TaskChildBean>()//任务bean，好像没什么用


    override fun observe(activity: BaseActivity<*, *>, owner: LifecycleOwner) {
        super.observe(activity, owner)
        scanType.observe(activity, Observer {
            if (it == Constants.TASK_NUMBER_RFID_BQXK) {
                activity.getTitleBar()?.setTitle("扫描背夹枪二维码")
            } else {
                activity.getTitleBar()?.setTitle(it)
            }
//            // 打开后置摄像头开始预览，但是并未开始识别
//            vBinding.zxingview.startCamera()
//            //设置回调
//            vBinding.zxingview.setDelegate(activity as ScanCodeAct)
            initScanType(it)
        })

        isOpen.observe(activity, Observer {
            vBinding.zxingview.let {
                if (isOpen.value!!) {
                    it.openFlashlight()
                    vBinding.ivSgd.setImageResource(R.mipmap.sgd_open)
                } else {
                    it.closeFlashlight()
                    vBinding.ivSgd.setImageResource(R.mipmap.sgd_close)
                }
            }
        })

        result.observe(activity, Observer {
            if (scanType.value == Constants.INTENT_TYPE_TASK_SM){
                httpSubmitSM(it)
            }else{
                App.post(EventMessage(EventCode.SCAN_CODE,it))
                activity.postDelayed({activity.finish()},1200)
            }
            activity.toast(it)
        })
    }

    /**
     * 初始化扫码类型
     */
    private fun initScanType(type: String?) {
        when (type) {
            //为空默认为扫描设备码连接设备
            //任务-RFID标签寻卡
            "", Constants.INTENT_TYPE_TASK_SM,Constants.INTENT_TYPE_ACTIVATION_SM, Constants.TASK_NUMBER_RFID_BQXK -> {
                //切换成扫描二维码样式
                vBinding.zxingview.changeToScanQRCodeStyle();
                //设置扫码类型   识别所有二维码
                vBinding.zxingview.setType(BarcodeType.TWO_DIMENSION, null);
            }
            Constants.INTENT_TYPE_TASK_EWMBD -> {//二维码绑定
                // 隐藏扫描框
                vBinding.zxingview.hiddenScanRect();
                //识别所有码
                vBinding.zxingview.setType(BarcodeType.ALL, null);
            }
        }
        // 显示扫描框，并开始识别
        vBinding.zxingview.startSpotAndShowRect()
    }


//    震动方法，好像没有用到
    @RequiresApi(Build.VERSION_CODES.O)
    private fun vibrate(activity: BaseActivity<*, *>) {
        val vibrator = activity.getSystemService(AppCompatActivity.VIBRATOR_SERVICE) as Vibrator
        vibrator.vibrate(VibrationEffect.createOneShot(200, VibrationEffect.DEFAULT_AMPLITUDE))
    }


    /**
     * 扫码成功
     */
    fun scanSuccess(result: String) {
        LogUtil.e("scan result:${result}")
         this.result.value = when{
            result.contains("���K����һ") -> result.replace("���K����һ", "吗冰K三合一")
            result.contains("���K���һ") -> result.replace("���K���һ", "吗冰K三合一")
            result.contains("���K����") -> result.replace("���K����", "吗冰K三合一")
            result.contains("����") -> result.replace("����", "冰毒")
            result.contains("ӫ��") -> result.replace("ӫ��", "荧光")
            result.contains("���") -> result.replace("���", "吗啡")
            else -> result
        }
    }
    /**
     * 光线变化
     */
    fun scanBrightnessChanged(isDark: Boolean) {
        // 这里是通过修改提示文案来展示环境是否过暗的状态，接入方也可以根据 isDark 的值来实现其他交互效果
        var tipText: String = vBinding.zxingview.scanBoxView.tipText.toString()//getScanBoxView().getTipText()
        val ambientBrightnessTip = "\n环境过暗，请打开闪光灯"
        if (isDark) {
            if (!tipText.contains(ambientBrightnessTip)) {
                vBinding.zxingview.scanBoxView.tipText = tipText + ambientBrightnessTip
            }
        } else {
            if (tipText.contains(ambientBrightnessTip)) {
                vBinding.zxingview.scanBoxView.tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip))
            }
        }
    }

    /**
     * 网络提交
     */
    private fun httpSubmitSM(result: String) {

    }

}